package com.tk.exam.web.restful;

import com.tk.exam.config.properties.SystemProperties;
import com.tk.exam.domain.TkFile;
import com.tk.exam.interceptor.NoCheckHttpHeader;
import com.tk.exam.service.TkFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;


@RestController
@RequestMapping("tk/exam/restful/file")
@Slf4j
public class ShowController {

    @Autowired
    SystemProperties systemProperties;
    @Autowired
    TkFileService tkFileService;

    private final ResourceLoader resourceLoader;

    @Autowired
    public ShowController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    /**
     * 显示单张图片
     *
     * @return
     */
    @RequestMapping(value = "show", produces = MediaType.IMAGE_JPEG_VALUE)
    @NoCheckHttpHeader
    public ResponseEntity showPhotos(String fileId, String filePath) {
        try {
            String absolutePath = "";
            if (StringUtils.isNotEmpty(fileId)) {
                TkFile tkFile = tkFileService.getTkFile(new Integer(fileId));
                absolutePath = tkFile.getFilePath();
            } else if (StringUtils.isNotEmpty(filePath)) {
                absolutePath = filePath;
            }
            if (StringUtils.isEmpty(absolutePath)) {
                return null;
            }
            absolutePath = systemProperties.getFileUploadPath() + File.separator + absolutePath;
            // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
            return ResponseEntity.ok(resourceLoader.getResource("file:" + absolutePath));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }


}
